package client.multisearch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import client.dtos.SearchRequest;

public class MultisearchManager {
	
	private final List<String> FIELDS = new ArrayList<String>();
	private final Map<String, Boolean> FIELD_STATES = new HashMap<String, Boolean>();
	private final Map<String, String> FIELD_VALUES = new HashMap<String, String>();
	
	public MultisearchManager() {
		FIELDS.add("Commit comment");
		FIELDS.add("Committer");
		FIELDS.add("Filename");
		
		for (String field : FIELDS) {
			FIELD_STATES.put(field, Boolean.FALSE);
		}
	}
	
	public List<String> getFieldNames() {
		return new ArrayList<String>(FIELDS);
	}
	
	public void enableField(final String fieldName) {
		checkField(fieldName);
		FIELD_STATES.put(fieldName, Boolean.TRUE);
	}
	
	public void disableField(final String fieldName) {
		checkField(fieldName);
		FIELD_STATES.put(fieldName, Boolean.FALSE);
	}
	
	private void checkField(String fieldName) {
		if (FIELDS.contains(fieldName)) {
			return;
		}
		throw new IllegalStateException("Unrecognised field name - "+ fieldName);
	}

	public void setFieldValue(final String fieldName, final String fieldValue) {
		checkField(fieldName);
		checkFieldEnabled(fieldName);
		FIELD_VALUES.put(fieldName, fieldValue);
	}

	private void checkFieldEnabled(String fieldName) {
		if (FIELD_STATES.get(fieldName)) {
			return;
		}
		throw new IllegalStateException("Cannot set value for field " + fieldName + " as it is currently disabled");
	}

	public boolean isFieldEnabled(final String fieldName) {
		checkField(fieldName);
		return FIELD_STATES.get(fieldName);
	}
	
	public String getFieldValue(final String fieldName) {
		return FIELD_VALUES.get(fieldName);
	}

	public SearchRequest getSearchRequest() {
		final SearchRequest sr = new SearchRequest();
		if (FIELD_STATES.get("Commit comment")) {
			sr.setCommitComment(FIELD_VALUES.get("Commit comment"));
		}
		if (FIELD_STATES.get("Committer")) {
			sr.setCommitter(FIELD_VALUES.get("Committer"));
		}
		if (FIELD_STATES.get("Filename")) {
			sr.setFileName(FIELD_VALUES.get("Filename"));
		}
		return sr;
	}

}
